#encoding=utf-8
'''
Created on 2016-07-09

@author: cooler
'''

import sys,os
reload(sys)
sys.setdefaultencoding('utf8')
sys.path.append("./")

import MySQLdb
from MySQLdb.cursors import DictCursor
from DBUtils.PooledDB import PooledDB
from Config import initConfig
import logging
import time
import random

logger = logging.getLogger('database')
logger.setLevel(logging.DEBUG)

config = initConfig()

class ArtMysql(object):
    """docstring for ArtMysql"""

    def __init__(self,write=False):
        self.write = write
        if write:
            self._conn_primary = ArtMysql.__db_session_write()
            self._cursor_primary = self._conn_primary.cursor(cursorclass=MySQLdb.cursors.DictCursor)
        else:
            self._conn_secondary = ArtMysql.__db_session_read()
            self._cursor_secondary = self._conn_secondary.cursor(cursorclass=MySQLdb.cursors.DictCursor)

    @staticmethod
    def __db_session_read():        
        try:
            read_num_start = int(config.get("mysql","read_num_start"))
            read_num_end = int(config.get("mysql","read_num_end"))
            read_num = str(random.randint(read_num_start,read_num_end))
            host = config.get("mysql","host_secondary"+read_num)
            port = int(config.get("mysql","port_secondary"+read_num))
            username = config.get("mysql","username_secondary"+read_num)
            password = config.get("mysql","password_secondary"+read_num)
            dbname = config.get("mysql","dbname_secondary"+read_num)
            conn = MySQLdb.connect(host = host,port=port,user = username,passwd = password,db = dbname,charset = 'utf8')
            return conn
        except Exception ,e:
            logger.info(str(e))
            logger.info("check second write db is normal !") 

    @staticmethod
    def __db_session_write():
        try:
            host = config.get("mysql","host_primary")
            port = int(config.get("mysql","port_primary"))
            username = config.get("mysql","username_primary")
            password = config.get("mysql","password_primary")
            dbname = config.get("mysql","dbname_primary")
            conn = MySQLdb.connect(host = host,port=port,user = username,passwd = password,db = dbname,charset = 'utf8')
            return conn
        except Exception ,e:
            logger.info(str(e))
        logger.info("check primary write db is normal !") 


    def initUpdateData(self,d):
        updateStr = ""
        print ",".join(d.keys())
        for k,v in d.items():
            if type(v) == int:
                print k,y,"float"
            else:
                print k,v,type(v)

    def getOne(self,sql):
        logger.info(str(sql))
        try:
            if self.write:
                self._cursor_primary.execute(sql)
                result = self._cursor_primary.fetchone()
            else:
                self._cursor_secondary.execute(sql)
                result = self._cursor_secondary.fetchone()
            return result
        except Exception, e:
            logger.info(str(sql))
            logger.exception(str(e))
            return False

    def getMany(self,sql):
        logger.info(str(sql))
        try:
            if self.write:
                self._cursor_primary.execute(sql)
                result = self._cursor_primary.fetchall()
            else:
                self._cursor_secondary.execute(sql)
                result = self._cursor_secondary.fetchall()
            return result
        except Exception, e:
            logger.info(str(sql))
            logger.exception(str(e))
            return False

    # def insert(self,table_name,data_dict):
    #     try:
    #         for k,v in data_dict:
    #             if type(v) == str:
    #                 pass
    #         sql = "insert into {0} ({1}) value({2})".format(",".join(data_dict.keys()))
    #     except Exception, e:
    #         logger.info(str(table_name)+","+str(data_dict))
    #         logger.exception(str(e))
    #         return False

    # def update(self,table_name,data_dict):
    #     try:
    #         pass
    #     except Exception, e:
    #         logger.info(str(table_name)+","+str(data_dict))
    #         logger.exception(str(e))
    #         return False

    def executeSQL(self,sql):
        try:
            logger.info(str(sql))
            res = self._cursor_primary.execute(sql)
            # self.end()
            return res
        except Exception, e:
            logger.info(str(sql))
            # print str(e)
            logger.info("excute sql failure : "+str(e))
            return False



    def end(self):
        """
        @summary: 结束事务
        """
        if self.write:
            self._conn_primary.commit()
        # self._cursor_primary.close()
        # self._cursor_primary.close()
        # self._conn_primary.close()
        # self._cursor_secondary.close()
        # self._conn_secondary.close()

    def rollback(self):
        if self.write:
            self._conn_primary.rollback()

    def close(self):
        if self.write:
            self._cursor_primary.close()
            self._conn_primary.close()
        else:
            self._cursor_secondary.close()
            self._conn_secondary.close()



if __name__ == '__main__':
    artmysql = ArtMysql()
    sql = "select count(*)  from xk_enroll  "
    res = artmysql.getMany(sql)
    print res
